package com.arlen.centre.controller;

import com.arlen.centre.exceptionHandle.WxException;
import com.arlen.centre.service.EventService;
import com.arlen.centre.service.WxRestoreMesService;
import com.arlen.common.constant.MesType;
import com.arlen.common.dto.CutInDTO;
import com.arlen.until.encrypt.EncryptSHA1Util;
import com.arlen.until.thread.WxMessageUuidThread;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Optional;

@Controller
@RequestMapping("cutIn")
public class CutInController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    EncryptSHA1Util encryptSHA1Util;

    @Value("${wx.token}")
    private String token;

    //微信验证
    @GetMapping
    public void verify(HttpServletResponse response, HttpServletRequest request) {
        Map<String, String[]> cutInMap = request.getParameterMap();
        try (PrintWriter writer = response.getWriter()) {
            if (cutInMap == null || cutInMap.size() < 4) {
                throw new IllegalStateException();
            }
            CutInDTO inDto = new CutInDTO();
            BeanUtils.populate(inDto, cutInMap);
            String[] ages = {inDto.getNonce(), inDto.getTimestamp(), token};
            String sha = encryptSHA1Util.dictionariesAndSha(ages);
            if (sha.equals(inDto.getSignature())) {
                writer.write(inDto.getEchostr());
            }
        } catch (IllegalStateException | IllegalAccessException | InvocationTargetException e) {
            logger.error("illegal request");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    WxRestoreMesService restoreMesService;

    @Autowired
    EventService eventService; //处理事件的服务

    @PostMapping
    public void handelMes(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        String uuid = WxMessageUuidThread.get();
        if (StringUtils.isBlank(uuid)){
            throw new WxException("Sometimes we do not achieve mes");
        }
        Map mesMao = (Map) redisTemplate.opsForValue().get(uuid);
        Optional<Map> optionalMap = Optional.ofNullable(mesMao);
        if (optionalMap.isPresent()){
            //调用解析服务进行解析
            String mes = null;
            try (PrintWriter writer = response.getWriter()){
                //处理事件  不知为何图片url总是接收不到
                String msgType = mesMao.get("MsgType").toString();
                if (MesType.EVENT.getType().equals(msgType)){
                    mes = eventService.analysisEvent(mesMao).toString();

                } else {
                    mes = restoreMesService.restoreMes(mesMao);
                    if (null == mes){
                        logger.error("Sometimes we do not achieve mes");
                    }
                }

                writer.write(mes);
            } catch (IOException | ClassNotFoundException e) {
                logger.error("Sometimes we do not achieve mes");
            } catch (IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }


        }else{
            logger.error("Sometimes we do not achieve mes");
            throw new WxException("Sometimes we do not achieve mes");
        }


    }


}
